
let client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });

let ScreenlocalTracks = {
  screenVideoTrack: null,
  audioTrack: null,
  screenAudioTrack: null,
};

let VideolocalTracks = {
  videoTrack: null,
  audioTrack: null,
};

/*
 * On initiation no users are connected.
 */
let remoteUsers = {};

(async () => {
  let res = await ajax('video_call_token', {
    channelName: window.location.href.split('/')[6].split('?')[1].split('&')[1].split('=')[1],
    userAccount: JSON.parse(localStorage.getItem('user')).user_id,
    uid: JSON.parse(localStorage.getItem('user')).user_id,
  }, 'post')
  localStorage.setItem('rtcToken', res.msg)
})()

let options = {
  // Pass your App ID here.
  appid: "69ee1d0f77224d1897d21a1d3bc56cd4",
  // Set the channel name.
  channel: window.location.href.split('/')[6].split('?')[1].split('&')[1].split('=')[1],
  // Pass your temp token here.
  token:
    localStorage.getItem('rtcToken'),
  // Set the user ID.
  uid: JSON.parse(localStorage.getItem('user')).user_id,
};





async function subscribe(user, mediaType) {
  const uid = user.uid;
  // subscribe to a remote user
  await client.subscribe(user, mediaType);
  console.log("subscribe success");
  if (mediaType === "video") {
    const player = $(`
      <div id="player-wrapper-${uid}" class='player-content'>
        <div id="player-${uid}" class="player"></div>
      </div>
    `);
    $(".interface-student-profile")[0].style.display = "none";
    $("#interface-teacher-join").append(player);
    user.videoTrack.play(`player-${uid}`);
  }
  if (mediaType === "audio") {
    user.audioTrack.play();
  }
}

/*
 * Add a user who has subscribed to the live channel to the local interface.
 *
 * @param  {IAgoraRTCRemoteUser} user - The {@link  https://docs.agora.io/en/Voice/API%20Reference/web_ng/interfaces/iagorartcremoteuser.html| remote user} to add.
 * @param {trackMediaType - The {@link https://docs.agora.io/en/Voice/API%20Reference/web_ng/interfaces/itrack.html#trackmediatype | media type} to add.
 */
function handleUserPublished(user, mediaType) {
  const id = user.uid;
  remoteUsers[id] = user;
  subscribe(user, mediaType);
}

async function VideoShare() {
  // Add an event listener to play remote tracks when remote user publishes.
  client.on("user-published", handleUserPublished);

  try {
    [options.uid, VideolocalTracks.audioTrack, VideolocalTracks.videoTrack] =
      await Promise.all([
        // Join the channel.
        client.join(
          options.appid,
          options.channel,
          options.token || null,
          options.uid || null
        ),
        // Create tracks to the local microphone and camera.
        AgoraRTC.createMicrophoneAudioTrack({
          AEC: true,
          AGC: true,
          ANS: true,
          encoderConfig: {
            sampleRate: 48000,
            stereo: true,
            bitrate: 128,
          },
        }),
        AgoraRTC.createCameraVideoTrack({
          encoderConfig: "1080p_5",
        }),
      ]);
    // Join a channel and create local tracks. Best practice is to use Promise.all and run them concurrently.
    // Play the local video track to the local browser and update the UI with the user ID.
    VideolocalTracks.videoTrack.play("interface-teacher-profile-content");
    console.log(`${options.uid}`);
    // Publish the local video and audio tracks to the channel.
    await client.publish(Object.values(VideolocalTracks));
    console.log("publish success");
  } catch (e) {
    Dreamer.error(e.message,2000)
  }

}

async function Videoleave() {
  Object.keys(VideolocalTracks).forEach((name) => {
    let track = VideolocalTracks[name];
    if (track) {
      track.stop();
      track.close();
      VideolocalTracks[name] = undefined;
    }
  });
  // remove remote users and player views
  remoteUsers = {};

  // leave the channel
  await client.leave();

  console.log("client leaves channel success");
}

async function ScreenShare() {
  // add event listener to play remote tracks when remote user publishs.
  client.on("user-published", handleUserPublished);

  let screenTrack;

  // join a channel and create local tracks, we can use Promise.all to run them concurrently
  [options.uid, ScreenlocalTracks.audioTrack, screenTrack] = await Promise.all([
    // join the channel
    client.join(
      options.appid,
      options.channel,
      options.token || null,
      options.uid || null
    ),
    // ** create local tracks, using microphone and screen
    AgoraRTC.createMicrophoneAudioTrack({
      AEC: true,
      AGC: true,
      ANS: true,
      encoderConfig: {
        sampleRate: 48000,
        stereo: true,
        bitrate: 128,
      },
    }),
    AgoraRTC.createScreenVideoTrack(
      {
        withAudio: 'enable',
        encoderConfig: {
          framerate: 60,
          height: 1080,
          width: 1920,
        },
      },
      "auto"
    ),
  ]);

  if (screenTrack instanceof Array) {
    ScreenlocalTracks.screenVideoTrack = screenTrack[0];
    ScreenlocalTracks.screenAudioTrack = screenTrack[1];
  } else {
    ScreenlocalTracks.screenVideoTrack = screenTrack;
  }
  // play local video track
  ScreenlocalTracks.screenVideoTrack.play("interface-teacher-profile-content");
  $("#local-player-name").text(`localVideo(${options.uid})`);

  //bind "track-ended" event, and when screensharing is stopped, there is an alert to notify the end user.
  ScreenlocalTracks.screenVideoTrack.on("track-ended", () => {
    alert(
      `Screen-share track ended, stop sharing screen ` +
      ScreenlocalTracks.screenVideoTrack.getTrackId()
    );
    ScreenlocalTracks.screenVideoTrack &&
      ScreenlocalTracks.screenVideoTrack.close();
  });

  // publish local tracks to channel
  if (ScreenlocalTracks.screenAudioTrack == null) {
    await client.publish([
      ScreenlocalTracks.screenVideoTrack,
      ScreenlocalTracks.audioTrack,
    ]);
  } else {
    await client.publish([
      ScreenlocalTracks.screenVideoTrack,
      ScreenlocalTracks.audioTrack,
      ScreenlocalTracks.screenAudioTrack,
    ]);
  }
  console.log("publish success");
}

async function Screenleave() {
  Object.keys(ScreenlocalTracks).forEach((name) => {
    let track = ScreenlocalTracks[name];
    if (track) {
      track.stop();
      track.close();
      ScreenlocalTracks[name] = undefined;
    }
  });
  // remove remote users and player views
  remoteUsers = {};

  // leave the channel
  await client.leave();

  console.log("client leaves channel success");
}

export { VideoShare, ScreenShare, Videoleave, Screenleave };
